using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;
using Microsoft.EntityFrameworkCore;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetUserPermissionsQueryHandler : IRequestHandler<GetUserPermissionsQuery, List<PermissionDto>>
	{
		private readonly IBaseRepository<UserRole> _userRoleRepo;
		private readonly IBaseRepository<RolePermission> _rolePermissionRepo;
		private readonly IBaseRepository<Permission> _permissionRepo;

		public GetUserPermissionsQueryHandler(
			IBaseRepository<UserRole> userRoleRepo,
			IBaseRepository<RolePermission> rolePermissionRepo,
			IBaseRepository<Permission> permissionRepo)
		{
			_userRoleRepo = userRoleRepo;
			_rolePermissionRepo = rolePermissionRepo;
			_permissionRepo = permissionRepo;
		}

		public async Task<List<PermissionDto>> Handle(GetUserPermissionsQuery request, CancellationToken cancellationToken)
		{
			// 获取用户角色ID
			var userRoleIds = _userRoleRepo.GetAll()
				.Where(x => ((UserRole)x).UserId == request.UserId)
				.Select(x => ((UserRole)x).RoleId)
				.ToList();

			if (!userRoleIds.Any())
			{
				return new List<PermissionDto>();
			}

			// 获取角色权限ID
			var permissionIds = _rolePermissionRepo.GetAll()
				.Where(x => userRoleIds.Contains(((RolePermission)x).RoleId))
				.Select(x => ((RolePermission)x).PermissionId)
				.Distinct()
				.ToList();

			if (!permissionIds.Any())
			{
				return new List<PermissionDto>();
			}

			// 获取权限信息
			var permissions = await _permissionRepo.GetAll()
				.Where(x => permissionIds.Contains(x.PermissionId) && x.IsActive)
				.Select(p => new PermissionDto
				{
					PermissionId = p.PermissionId,
					Name = p.Name,
					Code = p.Code,
					Group = p.Group,
					Description = p.Description,
					IsMenu = p.IsMenu,
					IsActive = p.IsActive,
					CreatedAt = p.CreatedAt,
					UpdatedAt = p.UpdatedAt
				})
				.Distinct()
				.ToListAsync(cancellationToken);

			return permissions;
		}
	}
}

